package authority.service;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import authority.comm.Lay;
import authority.comm.Message;
import authority.dao.UserDao;
import authority.dao.UserRoleDao;
import authority.entity.User;
import authority.entity.UserRole;
import authority.util.DbBuilder;
import authority.util.ExportExcelUtils;
import org.apache.log4j.Logger;

/**
 * 用户服务
 * 
 * @author shichenyang
 * 
 */
public class UserService {
	private static Logger logger= Logger.getLogger(UserService.class);
	private UserDao dao = new UserDao();

	private UserRoleDao userRoleDao = new UserRoleDao();

	// 登录
	public Message login(User user, HttpServletRequest request) {
		Connection connection = DbBuilder.getConnection();// 获取链接
		DbBuilder.beginTransaction(connection);// 开启事务
		Message m = new Message();
		// 进行用户查询
		user = dao.loginUser(user, connection);
		// 如果能够登录，查询出用户下所有权限
		if (user != null) {
			user = dao.loadPermission(user, connection);
			request.getSession().setAttribute("user", user);// 将查出来的权限放置到用户类里
			m.setState(true);
			m.setMeg("登录成功");
		} else {
			m.setState(false);
			m.setMeg("登录失败，账号或密码异常");
			m.setO(null);
		}
		DbBuilder.close(connection);// 关闭链接
		return m;
	}

	// 分页
	public Lay findListByPage(Lay lay, User user, String startDate,
			String endDate) {
		List<User> l = dao.findUserPage(user, startDate, endDate, lay);
		Integer count = dao.countUser(user, startDate, endDate);
		lay.setData(l);
		lay.setCount(count);
		return lay;
	}

	/**
	 * 导出用户列表
	 * @param user
	 * @param startDate
	 * @param endDate
	 * @param response
	 */
	public void expUser(User user, String startDate, String endDate,
			HttpServletResponse response) {
		//设置标题
		String[] rowsName = new String[] { "编号", "用户ID", "用户昵称", "用户真实姓名" };
		List<User> l = dao.findUser(user, startDate, endDate);//获取从数据库拿到的数据
		List<Object[]> dataList = new ArrayList<Object[]>();//导出集合
		String title = "用户信息表";//sheet名称
		Object[] objs = null;
		for (int i = 0; i < l.size(); i++) {//
			User u = l.get(i);
			objs = new Object[rowsName.length];
			objs[0] = i;
			objs[1] = u.getId();
			objs[2] = u.getName();
			objs[3] = u.getRealName();

			dataList.add(objs);
		}
		//导出excel帮助类
		ExportExcelUtils utils=new ExportExcelUtils(title, rowsName, dataList, response);
		utils.exportData();

	}
	/**
	 * 删除用户
	 * @param id
	 * @return
	 */
	public Message delUser(String id){
		Message message = new Message();
		try {
			dao.delUser(id);
			message.setState(true);
			message.setMeg("删除用户成功");
		} catch (Exception e) {
			message.setMeg("删除用户失败");
		}
		return message;
	}

	//修改用户
	public Message updateUser(User user, String[] role, User u){
		Message message = new Message();
		Connection connection = DbBuilder.getConnection();
		DbBuilder.beginTransaction(connection);
		try {
			user.setUpdateTime(new Date());
			user.setOper(u.getId());
			int i= dao.updateUser(user);
			logger.info("返回值"+i);
			message.setState(true);
			message.setMeg("修改用户成功");
			DbBuilder.commit(connection);
		} catch (Exception e) {
			e.printStackTrace();
			DbBuilder.rollback(connection);
			message.setState(false);
			message.setMeg("很抱歉，修改用户失败了");
		} finally {
			DbBuilder.close(connection);
		}
		return message;
	}

	// 添加用户
	public Message addUser(User user, String[] role, User u) {
		Message message = new Message();
		Connection connection = DbBuilder.getConnection();
		DbBuilder.beginTransaction(connection);
		// 1.向用户表添加数据
		try {
			String uid = UUID.randomUUID().toString();
			user.setId(uid);
			user.setCreateTime(new Date());
			user.setStatus("1");
			user.setUpdateTime(new Date());
			user.setOper(u.getId());
			dao.addUser(user);

			if(role!=null){
				for (int i = 0; i < role.length; i++) {
					UserRole userRole = new UserRole();
					userRole.setId(UUID.randomUUID().toString());
					userRole.setRid(role[i]);
					userRole.setUid(uid);
					userRole.setCreateTime(new Date());
					userRole.setUpdateTime(new Date());
					userRole.setOper(u.getName());
					userRole.setStastus("1");
					userRoleDao.save(userRole);
				}
			}
			
			message.setState(true);
			message.setMeg("添加用户成功");
			DbBuilder.commit(connection);
		} catch (Exception e) {
			e.printStackTrace();
			DbBuilder.rollback(connection);
			message.setState(false);
			message.setMeg("很抱歉，添加用户失败了");
		} finally {
			DbBuilder.close(connection);
		}
		return message;
	}
}
